local vector2d = require("Vector2D")

M = {}

local applyGravity = function(player, planetGroup)
    local gravity_constant = 8000
    
    if (player.planeta == nil) then
        for i = 1, planetGroup.numChildren do
            
            local vp = vector2d:new(player.x, player.y)
            local vi = vector2d:new(planetGroup[i].x, planetGroup[i].y)
            vi:sub(vp)
            local magnitud = vi:magnitude()
            vi:normalize()
            local mag2 = magnitud * magnitud * 1.2
            local fuerza = gravity_constant / mag2
            vi:mult(fuerza)
            player:applyForce(vi.x, vi.y, player.x, player.y)
        end
        --print("vuela")
    else
        local vp = vector2d:new(player.x, player.y)
        local vi = vector2d:new(player.planeta.x, player.planeta.y)
        vi:sub(vp)
        local magnitud = vi:magnitude()
        vi:normalize()
        local mag2 = magnitud * magnitud
        local fuerza = gravity_constant / mag2
        vi:mult(fuerza)
        player:applyForce(vi.x, vi.y, player.x, player.y)
        --print("planeta")
    end
    
    
end

M.applyGravity = applyGravity

local jump = function(player)
    local vp = vector2d:new(player.x, player.y)
    local vi = vector2d:new(player.planeta.x, player.planeta.y)
    vp:sub(vi)
    vp:normalize()
    player:applyLinearImpulse(vp.x / 2.5, vp.y / 2.5, player.x, player.y)
    
end

M.jump = jump

local speed = function(player)
    --velocidad en planeta
    local vp = vector2d:new(player:getLinearVelocity())
    if (player.planeta ~= nil and vp:magnitude() < 180) then
        local vp = vector2d:new(player:getLinearVelocity())
        vp:normalize()
        vp:mult(0.15)
        player:applyForce(vp.x, vp.y, player.x, player.y)
    end
end

M.speed = speed

return M